package com.web.news.servlet;

import java.io.IOException;
import java.util.function.DoubleToLongFunction;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.web.news.pojo.Users;
import com.web.news.service.UserService;
import com.web.news.service.impl.UserServiceImpl;

/**
 * Servlet implementation class UserServlet
 */
public class UserServlet extends HttpServlet {


	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("utf-8");	
		String action = request.getParameter("action");
		
		if("doLogin".equals(action)){
			doLogin(request,response);
		} else if("doLogout".equals(action)){
			//销毁session
			doLogout(request,response);
		}
		

	}

	private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		session.invalidate();
		response.sendRedirect(request.getContextPath() + "/NewsServlet?action=listNews"); 
	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		String uname = request.getParameter("uname");
		String password = request.getParameter("upwd");
		
		UserService userService = new UserServiceImpl();
		Users loginUser = userService.login(uname, password);
		if (loginUser!=null){
			HttpSession session = request.getSession();
			session.setAttribute("user", loginUser);
		} 
		response.sendRedirect(request.getContextPath() + "/NewsServlet?action=listNews"); 
	}

}
